package net.mihome.app.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.AppManager;
import net.mihome.app.R;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.common.UpdateManager;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.Map;

/**
 * 用户专属页面
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class MineFragment extends Fragment {
    User user;
    ImageView headIv;
    TextView userNameIv;
    LinearLayout myinfoLinearLayout;
    LinearLayout mydazibaoLinearLayout;
    LinearLayout myFriendLinearLayout;
    LinearLayout erweimaLinearLayout;
    LinearLayout updateLinearLayout;
    LinearLayout logoutLinearLayout;
    LinearLayout banjiaLinearLayout;
    TextView addressTextView;
    LinearLayout resetPasswordLinearLayout;
    Button logoutButton;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
        View mainView= inflater.inflate(R.layout.mine_fragment,null,false);
        user= AppContext.getInstance().getLoginInfo();
        headIv= (ImageView) mainView.findViewById(R.id.user_info_userface);
        userNameIv= (TextView) mainView.findViewById(R.id.user_info_username);
        myinfoLinearLayout= (LinearLayout) mainView.findViewById(R.id.main_myinfo_linearlayout);
        mydazibaoLinearLayout= (LinearLayout) mainView.findViewById(R.id.my_dazibao_linearlayout);
        addressTextView= (TextView) mainView.findViewById(R.id.user_info_address);
        myFriendLinearLayout= (LinearLayout) mainView.findViewById(R.id.my_friend_linearlayout);
        myFriendLinearLayout.setOnClickListener(qrListener);
//        myFriendLinearLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Uri uri= Uri.parse("smsto://");
//                Intent ii=new Intent(Intent.ACTION_SENDTO,uri);//绿色文字就是启动发送短信窗口
//                ii.putExtra("sms_body", "您好，我正在使用米宅App，对我的生活很有帮助，诚邀您加入进来。http://210.45.241.195:8181/images/mihomeandroidapp-release-0.9.9.1.apk");
//                startActivity(ii);
//            }
//        });
        banjiaLinearLayout= (LinearLayout) mainView.findViewById(R.id.banjia_linearlayout);
        banjiaLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getActivity(),SearchCommunityActivity.class);
                startActivity(intent);
            }
        });
        erweimaLinearLayout= (LinearLayout) mainView.findViewById(R.id.my_qc_linearlayout);
        updateLinearLayout= (LinearLayout) mainView.findViewById(R.id.update_linearlayout);
        logoutLinearLayout= (LinearLayout) mainView.findViewById(R.id.logout_linearlayout);
        resetPasswordLinearLayout= (LinearLayout) mainView.findViewById(R.id.reset_password_linearlayout);
        logoutButton= (Button) mainView.findViewById(R.id.logout_btn);
        if(user==null){
            Toast.makeText(getActivity(),"用户信息无效，请重新登录",Toast.LENGTH_LONG).show();
            return mainView;
        }
        ImageLoader.getInstance().displayImage(user.getFace(),headIv);
        userNameIv.setText(user.getAccount());
        addressTextView.setText(user.getCommunityName());
        logoutButton.setOnClickListener(logoutListener);
        logoutLinearLayout.setOnClickListener(logoutCancleListener);
        mydazibaoLinearLayout.setOnClickListener(myDazibaoListener);
        myinfoLinearLayout.setOnClickListener(myInfoListener);
        headIv.setOnClickListener(myInfoListener);
        updateLinearLayout.setOnClickListener(checkUpdateListener);
        erweimaLinearLayout.setOnClickListener(qrListener);
        resetPasswordLinearLayout.setOnClickListener(resetPasswordListener);
        return mainView;
    }
    //退出事件
    View.OnClickListener logoutListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EMChatManager.getInstance().logout();//此方法为同步方法
            AppManager.getAppManager().finishActivity(getActivity());
        }
    };
    //注销事件
    View.OnClickListener logoutCancleListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UIHelper.loginOrLogout(getActivity());
        }
    };
    //我的大字报
    View.OnClickListener myDazibaoListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(user!=null&&user.getUid()!=-1){
                Intent intent=new Intent(getActivity(),DazibaoActivity.class);
                intent.putExtra("id",user.getUid());
                startActivity(intent);
            }else{
                UIHelper.showAlertDialog(getActivity(),"提示","用户信息无效");
            }
        }
    };
    //我的资料
    View.OnClickListener myInfoListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UIHelper.showUserInfo(getActivity());
        }
    };
    //检查更新

    View.OnClickListener checkUpdateListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UpdateManager.getUpdateManager().checkAppUpdate(getActivity(), true);
        }
    };
    //二维码
    View.OnClickListener qrListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LayoutInflater factory = LayoutInflater.from(getActivity());
            final View dialogView = factory.inflate(R.layout.qr_dialog, null);
            ImageView qriv= (ImageView) dialogView.findViewById(R.id.qr_imageview);
            Button cancleBtn= (Button)dialogView.findViewById(R.id.btn_cancel);
            Button okBtn= (Button) dialogView.findViewById(R.id.btn_ok);
            ImageLoader.getInstance().displayImage(URLs.MIHOME_UPDATE_ANDROID_QR,qriv);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setView(dialogView);
            final AlertDialog alertDialog=builder.create();
            alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            cancleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
            okBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Uri uri= Uri.parse("smsto://");
                    Intent ii=new Intent(Intent.ACTION_SENDTO,uri);//绿色文字就是启动发送短信窗口
                    ii.putExtra("sms_body", getResources().getString(R.string.yaoqing_sms));
                    startActivity(ii);
                    alertDialog.dismiss();
                }
            });
            alertDialog.show();
        }
    };
    //修改密码
    View.OnClickListener resetPasswordListener= new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LayoutInflater factory = LayoutInflater.from(getActivity());
            final View dialogView = factory.inflate(R.layout.reset_password_dialog, null);
            Button cancleBtn= (Button)dialogView.findViewById(R.id.btn_cancel);

            final EditText editText= (EditText) dialogView.findViewById(R.id.edit);
            final EditText editTextOld= (EditText) dialogView.findViewById(R.id.edit_old);
            final TextView textView= (TextView) dialogView.findViewById(R.id.alert_message);
            Button okBtn= (Button) dialogView.findViewById(R.id.btn_ok);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setView(dialogView);
            final AlertDialog alertDialog=builder.create();
            alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            cancleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
            okBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(editText.getText()==null||editText.getText().toString()==null||"".equals(editText.getText().toString().trim())){
                        textView.setText("新密码不能为空");
                        return ;
                    }
                    if(editTextOld.getText()==null||editTextOld.getText().toString()==null||"".equals(editTextOld.getText().toString().trim())){
                        editTextOld.setText("新密码不能为空");
                        return ;
                    }
                    textView.setText("正在修改...");
                    editText.setEnabled(false);
                    editTextOld.setEnabled(false);
                    RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
                    requestParams.put("password", editText.getText().toString());
                    requestParams.put("password_old", editTextOld.getText().toString());
                    AppContext.ASYNC_HTTP_CLIENT.get(getActivity(),URLs.MIHOME_USER_RESET_PASSWORD,requestParams,new MiAsyncHttpResponseHandler<Map>() {
                        @Override
                        public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                            Toast.makeText(getActivity(),"修改成功",Toast.LENGTH_SHORT).show();
                            alertDialog.dismiss();
                        }

                        @Override
                        public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                            textView.setText("修改失败，"+arg3.getMessage());
                            editText.setEnabled(true);
                            editTextOld.setEnabled(true);
                        }
                    });
                }
            });
            alertDialog.show();
        }
    };
}
